package com.dxyxx.framework;

import java.lang.ref.WeakReference;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.smssdk.SMSSDK;

import com.android.customized.BadgeView;
import com.dxyxx.R;
import com.dxyxx.android.setting.GetstartPreferences;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.db.BadgeContentObserver;
import com.dxyxx.db.DataChangeProvider;
import com.dxyxx.db.DataQueryUtils;
import com.dxyxx.db.ShoppingCarContentObserver;
import com.dxyxx.framework.BuyProductActivity.MyInnerHandler;
import com.dxyxx.getstart.ViewPagerActivity;
import com.dxyxx.pojo.User;
import com.dxyxx.utils.UpdateManager;

/**
 * UI描述：多tab界面，底层多tab,有五个tab，分别是 首页、品类、我的果园、购物车、热评
 * 
 * ActivityGroup太难掌控了， 可以使用Fragment来替代 WindowManager manager = (WindowManager)
 * context.getSystemService(Context.WINDOW_SERVICE); Display display =
 * manager.getDefaultDisplay(); int width = display.getWidth(); // 屏幕高度（像素） int
 * topBannerHeight = (int) (width / (640.0 / 320));
 * realHeader.findViewById(R.id.adgallery);
 * 
 * @author chinesejie@qq.com
 * 
 */
public class FragmentMainActivity extends FragmentActivity {

	/**
	 * 4 个 fragment
	 */
	private HomepageFragment mTab01;
	private CategoryFragment mTab02;
	private MyCenterFragment mTab03;
	private ShoppingCarFragment mTab04;
	private CommentFragment mTab05;
	// 声明LocalActivityManager对象，不用了， tab不支持滑动
	// private GestureDetector m_GestureDetector;
	// private LocalActivityManager localActivityManager;

	private ImageView homepageImage; // 首页
	private ImageView categoryImage; // 品类
	private ImageView myCenterImage; // 我的果园
	private ImageView shoppingCarImage;// 购物车
	private ImageView commentImage; // 热评

	private LinearLayout homepageLayout;
	private LinearLayout categoryLayout;
	private LinearLayout myCenterLayout;
	private LinearLayout shoppingCarLayout;
	private LinearLayout commentLayout;

	private TextView homepageText; // 首页
	private TextView categoryText; // 品类
	private TextView myCenterText; // 我的果园
	private TextView shoppingCarText;// 购物车
	private TextView commentText; // 热评

	private int defaultTextColore;
	private int themeTextColore;
	/**
	 * 用于对Fragment进行管理
	 */
	private FragmentManager fragmentManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// 判断 是否第一次启动，是的话启动 ViewPagerActivity
		//		if (!GetstartPreferences.getInstance(FragmentMainActivity.this).getFlag()) {
		//			startActivity(new Intent(FragmentMainActivity.this, ViewPagerActivity.class));
		//		}

		super.onCreate(savedInstanceState);
		try {
			UpdateManager um = new UpdateManager(FragmentMainActivity.this);
			um.checkUpdateInfo();
		} catch (Exception e) {

		}
		//为了短信 
		SMSSDK.initSDK(this, "646c79aecc19", "6f3e2e71d1d92a826a4f46bc238e8e14");
		setContentView(R.layout.activity_fragmentmain);
		initViews();
		fragmentManager = getSupportFragmentManager();
		defaultTextColore = categoryText.getCurrentTextColor();
		themeTextColore = homepageText.getCurrentTextColor();
		setTabSelection(0);
		bindListener();
	}

	/**
	 * 根据传入的index参数来设置选中的tab页。
	 * 
	 */
	private void setTabSelection(int index) {
		// 重置按钮
		// resetBtn();
		// 开启一个Fragment事务
		FragmentTransaction transaction = fragmentManager.beginTransaction();

		// transaction.setCustomAnimations(R.anim.push_left_in,
		// R.anim.push_left_out, R.anim.push_right_in, R.anim.push_right_out);

		// 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
		hideFragments(transaction);
		switch (index) {
		case 0:
			changeBackground(0);
			if (mTab01 == null) {
				// 如果MessageFragment为空，则创建一个并添加到界面上
				mTab01 = new HomepageFragment();

				transaction.add(R.id.id_content, mTab01);
			} else {
				// 如果MessageFragment不为空，则直接将它显示出来
				transaction.show(mTab01);
			}
			break;
		case 1:
			changeBackground(1);
			if (mTab02 == null) {
				// 如果MessageFragment为空，则创建一个并添加到界面上
				mTab02 = new CategoryFragment();
				transaction.add(R.id.id_content, mTab02);
			} else {
				// 如果MessageFragment不为空，则直接将它显示出来
				transaction.show(mTab02);
			}
			break;
		case 2:
			changeBackground(2);
			if (mTab03 == null) {
				// 如果NewsFragment为空，则创建一个并添加到界面上
				mTab03 = new MyCenterFragment();
				transaction.add(R.id.id_content, mTab03);
			} else {
				// 如果NewsFragment不为空，则直接将它显示出来
				transaction.show(mTab03);
			}
			break;
		case 3:
			changeBackground(3);
			if (mTab04 == null) {
				// 如果SettingFragment为空，则创建一个并添加到界面上
				mTab04 = new ShoppingCarFragment();
				transaction.add(R.id.id_content, mTab04);
			} else {
				// 如果SettingFragment不为空，则直接将它显示出来
				transaction.show(mTab04);
			}
			break;

		case 4:
			changeBackground(4);
			if (mTab05 == null) {
				// 如果SettingFragment为空，则创建一个并添加到界面上
				mTab05 = new CommentFragment();
				transaction.add(R.id.id_content, mTab05);
			} else {
				// 如果SettingFragment不为空，则直接将它显示出来
				transaction.show(mTab05);
			}
			break;
		}
		//transaction.commit();
		transaction.commitAllowingStateLoss();
	}

	public void bindListener() {
		homepageLayout.setOnClickListener(new ImageView.OnClickListener() {
			public void onClick(View v) {
				setTabSelection(0);
			}
		});
		categoryLayout.setOnClickListener(new ImageView.OnClickListener() {
			public void onClick(View v) {
				setTabSelection(1);
			}
		});
		myCenterLayout.setOnClickListener(new ImageView.OnClickListener() {
			public void onClick(View v) {
				setTabSelection(2);
			}
		});
		shoppingCarLayout.setOnClickListener(new ImageView.OnClickListener() {
			public void onClick(View v) {
				setTabSelection(3);

			}
		});
		commentLayout.setOnClickListener(new ImageView.OnClickListener() {
			public void onClick(View v) {
				setTabSelection(4);
			}
		});
	}

	private void initViews() {

		// 十大控件
		homepageLayout = (LinearLayout) findViewById(R.id.core_main_homepage_layout);
		categoryLayout = (LinearLayout) findViewById(R.id.core_main_category_layout);
		myCenterLayout = (LinearLayout) findViewById(R.id.core_main_myCenter_layout);
		shoppingCarLayout = (LinearLayout) findViewById(R.id.core_main_shoppingCar_layout);
		commentLayout = (LinearLayout) findViewById(R.id.core_main_comment_layout);
		homepageImage = (ImageView) findViewById(R.id.core_main_homepage);
		categoryImage = (ImageView) findViewById(R.id.core_main_category);
		myCenterImage = (ImageView) findViewById(R.id.core_main_myCenter);
		shoppingCarImage = (ImageView) findViewById(R.id.core_main_shoppingCar);
		commentImage = (ImageView) findViewById(R.id.core_main_comment);

		homepageText = (TextView) findViewById(R.id.homepageText);
		categoryText = (TextView) findViewById(R.id.categoryText);
		myCenterText = (TextView) findViewById(R.id.myCenterText);
		shoppingCarText = (TextView) findViewById(R.id.shoppingCarText);
		commentText = (TextView) findViewById(R.id.commentText);

		// 设置 购物车监听、
		badge = new BadgeView(this, shoppingCarImage);
		int num = DataQueryUtils.getProductsCount(getApplicationContext(), DataChangeProvider.CONTENT_URI);
		if (num != 0) {
			badge.setText(num + "");
			badge.show();
		}

	}

	/**
	 * 监听本Activity中所要监听的对象
	 */
	// public void bindListener() {
	// homepageLayout.setOnClickListener(new ImageView.OnClickListener() {
	// public void onClick(View v) {
	// moveToSpecifiedTab(getApplicationContext(), 0);
	// }
	// });
	// categoryLayout.setOnClickListener(new ImageView.OnClickListener() {
	// public void onClick(View v) {
	// moveToSpecifiedTab(getApplicationContext(), 1);
	// }
	// });
	// myCenterLayout.setOnClickListener(new ImageView.OnClickListener() {
	// public void onClick(View v) {
	// moveToSpecifiedTab(getApplicationContext(), 2);
	// }
	// });
	// shoppingCarLayout.setOnClickListener(new ImageView.OnClickListener() {
	// public void onClick(View v) {
	// moveToSpecifiedTab(getApplicationContext(), 3);
	//
	// }
	// });
	// commentLayout.setOnClickListener(new ImageView.OnClickListener() {
	// public void onClick(View v) {
	// moveToSpecifiedTab(getApplicationContext(), 4);
	// }
	// });
	// }

	public void changeBackground(int num) {
		homepageLayout.setBackgroundResource(R.color.transparent);
		categoryLayout.setBackgroundResource(R.color.transparent);
		myCenterLayout.setBackgroundResource(R.color.transparent);
		shoppingCarLayout.setBackgroundResource(R.color.transparent);
		commentLayout.setBackgroundResource(R.color.transparent);

		homepageImage.setImageResource(R.drawable.homepage_transparent);
		categoryImage.setImageResource(R.drawable.category_transparent);
		myCenterImage.setImageResource(R.drawable.mycenter_transparent);
		shoppingCarImage.setImageResource(R.drawable.shoppingcar_transparent);
		commentImage.setImageResource(R.drawable.comment_transparent);

		homepageText.setTextColor(defaultTextColore);
		categoryText.setTextColor(defaultTextColore);
		myCenterText.setTextColor(defaultTextColore);
		shoppingCarText.setTextColor(defaultTextColore);
		commentText.setTextColor(defaultTextColore);

		switch (num) {
		case 0:
			homepageImage.setImageResource(R.drawable.homepage_transparent_click);
			homepageText.setTextColor(themeTextColore);
			break;
		case 1:
			categoryImage.setImageResource(R.drawable.category_transparent_click);
			categoryText.setTextColor(themeTextColore);
			break;
		case 2:
			myCenterImage.setImageResource(R.drawable.mycenter_transparent_click);
			myCenterText.setTextColor(themeTextColore);
			break;
		case 3:
			shoppingCarImage.setImageResource(R.drawable.shoppingcar_transparent_click);
			shoppingCarText.setTextColor(themeTextColore);
			break;
		case 4:
			commentImage.setImageResource(R.drawable.comment_transparent_click);
			commentText.setTextColor(themeTextColore);
			break;

		default:
			break;
		}
	}

	// @Override
	// public boolean onTouch(View v, MotionEvent event) {
	// // 一定要将触屏事件交给手势识别类去处理(自己处理会很麻烦的)
	// return false;
	// }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false; // 屏蔽返回键
	}

	/**
	 * 将所有的Fragment都置为隐藏状态。
	 * 
	 * @param transaction
	 *            用于对Fragment执行操作的事务
	 */
	public void hideFragments(FragmentTransaction transaction) {
		if (mTab01 != null) {
			transaction.hide(mTab01);
		}
		if (mTab04 != null) {
			transaction.hide(mTab04);
		}
		if (mTab02 != null) {
			transaction.hide(mTab02);
		}
		if (mTab03 != null) {
			transaction.hide(mTab03);
		}
		if (mTab05 != null) {
			transaction.hide(mTab05);
		}

	}

	// 重新登录 得到token

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null) {
			Object result = data.getExtras().get("result");
			switch (requestCode) {
			case RequestCode.MyOrder:
				startActivity(new Intent(FragmentMainActivity.this, OrderListActivity.class));
				break;
			case RequestCode.MyQr:
				startActivity(new Intent(FragmentMainActivity.this, ScanActivity.class));
				break;
			case RequestCode.MyGroupOrder:
				startActivity(new Intent(FragmentMainActivity.this, GroupOrderListActivity.class));
				break;
			case RequestCode.MyTicket:
				startActivity(new Intent(FragmentMainActivity.this, TicketActivity.class));
				break;
			case RequestCode.BuyTicket:
				startActivity(new Intent(FragmentMainActivity.this, BuyTicketActivity.class));
				break;
			case RequestCode.MyComment:
				//刷新我的评论 界面
				mTab05.callMyCommentsNetwork();
				break;
			case RequestCode.MyReply:
				//提交评论 postreply()
				mTab05.postreply();
				break;

			default:
				break;
			}
			switch (resultCode) {
			// 调用购物车页面 
			case ResultCode.Product:
				if (result.equals("cart")) {
					setTabSelection(3);
				}
				break;
			case ResultCode.Login: //更新user info，每次登陆都会触发这个条件
				//调用 MyCenterragment 的静态方法。
				if (mTab03 != null) {// 有可能这个页面 还没有出来
					mTab03.callNetwork();// 更新 用户数据, 不包括更新 手机号 跟密码
				}
				if (mTab05 != null) {// 有可能这个页面 还没有出来
					mTab05.callMyCommentsNetwork();// 更新 用户数据
				}
				break;

			case ResultCode.CommentSuccess:
				mTab05.refreshMyCommentsNetwork();//更新我的评论
				break;

			case ResultCode.Logout:
				finish();//更新我的评论
				break;

			case ResultCode.Info:
				User user = (User) data.getExtras().get("result");
				if (user != null) {
					// 更新 用户数据, 不包括更新 手机号 跟密码
					mTab03.setUserInfoOnView(user);
				}
				break;

			default:
				break;
			}

		}
	}

	//** 避免  handler 内存泄露。 见http://stackoverflow.com/questions/11278875/handlers-and-memory-leaks-in-android
	static class MyInnerHandler extends Handler {
		WeakReference<FragmentMainActivity> mActivity;

		MyInnerHandler(FragmentMainActivity activity) {
			mActivity = new WeakReference<FragmentMainActivity>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			FragmentMainActivity theActivity = mActivity.get();
			if (theActivity != null) {

				int count = DataQueryUtils.getProductsCount(theActivity.getApplicationContext(), DataChangeProvider.CONTENT_URI);
				if (count != 0) {
					// 更新 个数
					theActivity.badge.setText(count + "");
					theActivity.badge.show();
				} else {
					theActivity.badge.hide();
				}
			}
		}
	}

	private MyInnerHandler myHandler = new MyInnerHandler(this);
	private BadgeContentObserver observer;
	private BadgeView badge;

	@Override
	public void onResume() {

		super.onResume();
		if (observer == null) {
			observer = new BadgeContentObserver(myHandler);
			getContentResolver().registerContentObserver(DataChangeProvider.CONTENT_URI, true, observer);
		}
		//设置监听
	}

	//删除监听..此处不能删除监听
	@Override
	public void onStop() {
		super.onStop();
		if (observer != null) {
			//getActivity().getContentResolver().unregisterContentObserver(shoppingCarContentObserver);
		}
	}
}